import plugin from '../../lib/plugins/plugin.js'
import { XiuXianData } from './xiuxian_data.js'
import { XiuXianUtils } from './xiuxian_utils.js'
import express from 'express'
import bodyParser from 'body-parser'
import path from 'path'
import fs from 'fs'

export class XiuXianAdmin extends plugin {
    constructor() {
        super({
            name: '修仙文游管理',
            dsc: '修仙游戏的管理功能',
            event: 'message',
            priority: 5000,
            rule: [
                { reg: '^#启动修仙管理$', fnc: 'startAdminServer', permission: 'master' }
            ]
        })
        this.data = new XiuXianData()
        this.utils = new XiuXianUtils()
        this.port = 26257 // 端口
        this.app = express()
        this.server = null
    }

    async startAdminServer(e) {
        if (this.server) {
            return this.reply('管理服务器已经在运行中');
        }

        try {
            const getPublicIP = async () => {
                const ipServices = [
                    'https://api.ipify.org?format=json',
                    'https://icanhazip.com',
                    'https://ifconfig.me/ip'
                ];

                for (let i = 0; i < 3; i++) {
                    for (const service of ipServices) {
                        try {
                            const response = await fetch(service);
                            if (service.includes('ipify')) {
                                const data = await response.json();
                                return data.ip;
                            } else {
                                return await response.text();
                            }
                        } catch (error) {
                            console.error(`从 ${service} 获取公网IP失败:`, error);
                        }
                    }
                    await new Promise(resolve => setTimeout(resolve, 1000));
                }
                console.error('无法获取公网IP');
                return null;
            };

            const getLocalIP = async () => {
                const os = await import('os');
                const interfaces = os.networkInterfaces();
                for (const devName in interfaces) {
                    const iface = interfaces[devName];
                    for (let i = 0; i < iface.length; i++) {
                        const alias = iface[i];
                        if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                            return alias.address;
                        }
                    }
                }
                return '127.0.0.1';
            };

            const publicIP = await getPublicIP();
            const localIP = await getLocalIP();
            const displayIP = publicIP || localIP;

            this.setupAdminServer();

            this.server = await new Promise((resolve, reject) => {
                const server = this.app.listen(this.port, () => {
                    resolve(server);
                });
                server.on('error', (err) => {
                    if (err.code === 'EADDRINUSE') {
                        reject(new Error(`端口 ${this.port} 已被占用，请先关闭占用该端口的程序`));
                    } else {
                        reject(err);
                    }
                });
            });
            this.reply(`管理服务器已启动，请访问 http://${displayIP}:${this.port}`);
        } catch (err) {
            this.reply(`启动管理服务器失败：${err.message}`);
        }
    }

    setupAdminServer() {
        const dataDir = path.join(process.cwd(), 'xiuxian Web')
        this.app.use(bodyParser.json());
        this.app.use(bodyParser.urlencoded({ extended: true }));
        this.app.use(express.static(path.join(dataDir, 'admin')));

        this.app.get('/', (req, res) => {
            res.sendFile(path.join(dataDir, 'admin', 'xiuxian.html'))
        })

        this.app.get('/api/users', (req, res) => {
            res.json(this.data.gameState);
        });

        this.app.post('/api/users/:userId', (req, res) => {
            const { userId } = req.params;
            const updatedData = req.body;
            this.data.gameState[userId] = { ...this.data.gameState[userId], ...updatedData };
            this.utils.saveJSON(this.data.paths.gameData, this.data.gameState);
            res.json({ success: true });
        });

        this.app.get('/api/realms', (req, res) => {
            res.json(this.data.realms);
        });

        this.app.post('/api/realms', (req, res) => {
            const { realm } = req.body;
            if (!this.data.realms.includes(realm)) {
                this.data.realms.push(realm);
                this.utils.saveJSON(this.data.paths.realms, this.data.realms);
            }
            res.json({ success: true });
        });

        this.app.delete('/api/realms/:index', (req, res) => {
            const index = parseInt(req.params.index);
            if (index >= 0 && index < this.data.realms.length) {
                this.data.realms.splice(index, 1);
                this.utils.saveJSON(this.data.paths.realms, this.data.realms);
            }
            res.json({ success: true });
        });

        this.app.get('/api/monsters', (req, res) => {
            res.json(this.data.monsters);
        });

        this.app.post('/api/monsters', (req, res) => {
            const { name, level } = req.body;
            this.data.monsters.push({ name, level: parseInt(level) });
            this.utils.saveJSON(this.data.paths.monsters, this.data.monsters);
            res.json({ success: true });
        });

        this.app.delete('/api/monsters/:index', (req, res) => {
            const index = parseInt(req.params.index);
            if (index >= 0 && index < this.data.monsters.length) {
                this.data.monsters.splice(index, 1);
                this.utils.saveJSON(this.data.paths.monsters, this.data.monsters);
            }
            res.json({ success: true });
        });

        this.app.get('/api/items', (req, res) => {
            res.json(this.data.shop);
        });

        this.app.post('/api/items', (req, res) => {
            const { name, price, effect } = req.body;
            if (!name || !price || !effect) {
                return res.status(400).json({ success: false, message: '缺少必要的参数' });
            }

            const newItem = {
                name,
                price: parseInt(price),
                effect: JSON.parse(effect)
            };

            this.data.shop.push(newItem);
            this.utils.saveJSON(this.data.paths.shop, this.data.shop);
            res.json({ success: true, message: '物品添加成功', item: newItem });
        });

        this.app.delete('/api/items/:name', (req, res) => {
            const name = decodeURIComponent(req.params.name);
            const initialLength = this.data.shop.length;
            this.data.shop = this.data.shop.filter(item => item.name !== name);

            if (this.data.shop.length < initialLength) {
                this.utils.saveJSON(this.data.paths.shop, this.data.shop);
                res.json({ success: true, message: '物品删除成功' });
            } else {
                res.status(404).json({ success: false, message: '物品未找到' });
            }
        });

        this.app.post('/api/login', (req, res) => {
            const { username, password } = req.body;
            // 读取存储账号密码的JSON文件
            const credentialsPath = path.join(process.cwd(), 'xiuxian Web', 'admin', 'credentials.json');
            let credentials;
            try {
                credentials = JSON.parse(fs.readFileSync(credentialsPath, 'utf8'));
            } catch (error) {
                console.error('读取凭据文件时出错:', error);
                return res.status(500).json({ success: false, message: '服务器错误' });
            }

            // 验证用户名和密码
            if (credentials['userName'] === username && credentials['password'] === password) {
                res.json({ success: true, message: '登录成功' });
            } else {
                res.status(401).json({ success: false, message: '用户名或密码错误', body: { username, password } });
            }
        });
    }
}
